﻿using System;
using System.Runtime.InteropServices;

namespace Net.System
{
    public unsafe struct UnmanagedArray<T> : IDisposable where T : unmanaged
    {
        private readonly T* _ptr;
        private int _length;
        private bool _isAllocated;

        public readonly int Length => _length;
        public readonly bool IsCreated => _isAllocated;

        public ref T this[int index]
        {
            get
            {
                if (index < 0 || index >= _length)
                    throw new IndexOutOfRangeException();
                return ref _ptr[index];
            }
        }

        public UnmanagedArray(int length)
        {
            if (length <= 0)
                throw new ArgumentException("Length must be positive.");

            _length = length;
            int size = sizeof(T) * length;
            _ptr = (T*)Marshal.AllocHGlobal(size); // 分配非托管内存
            _isAllocated = true;
        }

        public void Dispose()
        {
            if (_isAllocated)
            {
                Marshal.FreeHGlobal((nint)_ptr); // 释放非托管内存
                _length = 0;
                _isAllocated = false;
            }
        }
    }
}